package xyz.labmem.controller

import cn.hutool.core.util.StrUtil
import javafx.animation.FadeTransition
import javafx.stage.StageStyle
import javafx.util.Duration
import xyz.labmem.config.BrowserReptileConfig
import xyz.labmem.core.annotation.FXController
import xyz.labmem.core.annotation.FXLoadController
import xyz.labmem.core.base.BaseController
import xyz.labmem.core.util.getResourceFile
import xyz.labmem.service.BrowserReptileSimpleServer
import java.util.*


/**
 * @Author lty
 * @Date 2021/9/13 10:39
 */
@FXController(title = "载入程序..", icon = "wicon.png")
@FXLoadController
class InitLoadingController : BaseController() {

    override fun controlInitDown() {
        root.scene.apply {
            fill = null
            stylesheets.add(getResourceFile("css/appLoading.css").url.toExternalForm())
        }
        stage.apply {
            isAlwaysOnTop = true
            width = 366.0
            height = 180.0
            initStyle(StageStyle.TRANSPARENT)
        }
    }

    /**
     * 加载初始化操作
     */
    override fun loadingInit() {
        val appController = request.getParams()["targetController"] as BrowserReptileController
        //启动服务
        appController.server = BrowserReptileSimpleServer(appController).apply {
            //获取驱动
            if (StrUtil.isBlank(BrowserReptileConfig.driverDir)) {
                var chromedriver = "$root${appController.STATIC_PATH}/chromedriver/"
                if (System.getProperty("os.name").lowercase(Locale.getDefault()).indexOf("windows") >= 0) {
                    chromedriver += "chromedriver.exe"
                    BrowserReptileConfig.refreshDriver(chromedriver)
                } else if (System.getProperty("os.name").lowercase(Locale.getDefault()).indexOf("linux") >= 0) {
                    chromedriver += "chromedriver-linux64"
                    BrowserReptileConfig.refreshDriver(chromedriver)
                    BrowserReptileConfig.chromePath = "/opt/apps/cn.google.chrome/files/google-chrome"
                }
            } else
                BrowserReptileConfig.refreshDriver()
//            else if (System.getProperty("os.name").lowercase(Locale.getDefault()).indexOf("mac") >= 0) {
//                chromedriver-linux64 += "chromedriver-linux64-mac64"
//            }

            //http
            create(appController.post).apply {
                start()
            }
            //socket
            socket(appController.socketPost)
        }

        FadeTransition(Duration.millis(600.0)).apply {
            fromValue = 1.0 // 设置起始透明度为1.0，表示不透明
            toValue = 0.0 // 设置结束透明度为0.0，表示透明
            node = root // 设置动画应用的节点
            play()
        }
        Thread.sleep(600)
    }

    override fun initialize() {
        super.initialize()
    }
}